package com.squareup.picasso;

import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;

import com.squareup.picasso.Picasso.LoadedFrom;

final class ImageViewAction extends Action<ImageView> {
    private Callback callback;

    ImageViewAction(Picasso picasso, ImageView imageView, Request data, int errorResId, String key, Callback callback) {
        super(picasso, imageView, data, errorResId, key);
        this.callback = callback;
    }

    public final void cancel() {
        super.cancel();
        if(this.callback != null) {
            this.callback = null;
        }
    }

    public final void complete(Drawable result, LoadedFrom from) {
        if(result == null) {
            throw new AssertionError(String.format("Attempted to complete action with no result!\n%s", this));
        }

        ImageView target = this.target.get();
        if(target != null) {
            if((result instanceof BitmapDrawable)) {
                PicassoDrawable.setBitmap(target, this.picasso.context, ((BitmapDrawable) result).getBitmap(), from, false);
            }

            if(this.callback == null) {
                return;
            }

            this.callback.onSuccess(result, from);
        }
    }

    public final void error(Exception e) {
        if(this.target.get() != null && this.callback != null) {
            this.callback.onError(e);
        }
    }
}

